package com.boatAnchorAssistant.service.service.impl;

import com.boatAnchorAssistant.pojo.dto.expandValue.UpdateExpandValueDto;
import com.boatAnchorAssistant.pojo.entity.ExpandField;
import com.boatAnchorAssistant.pojo.entity.ExpandValue;
import com.boatAnchorAssistant.service.repository.in.ExpandFieldRepository;
import com.boatAnchorAssistant.service.repository.in.ExpandValueRepository;
import com.boatAnchorAssistant.service.service.in.ExpandValueService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 【描 述】：
 * 【环 境】：J2SE 17
 * 【详 细】：
 *
 * @author 李松林
 * @version v1.0 2024/6/11 新建
 * @since 2024/6/11
 */
@Service
public class ExpandValueServiceImpl implements ExpandValueService {

    private final ExpandValueRepository expandValueRepository;


    private final ExpandFieldRepository expandFieldRepository;

    public ExpandValueServiceImpl(ExpandValueRepository expandValueRepository, ExpandFieldRepository expandFieldRepository) {
        this.expandValueRepository = expandValueRepository;
        this.expandFieldRepository = expandFieldRepository;
    }

    /**
     * 更新拓展值
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateExpandValue(UpdateExpandValueDto dto) {
        Long recordId = dto.getRecordId();
        expandValueRepository.clean(recordId);

        String model = dto.getModel();
        Map<String, String> expandData = dto.getExpandData();

        ExpandField t = new ExpandField();
        t.setModel(model);
        List<ExpandField> fieldList = expandFieldRepository.getListByEntity(t);

        List<ExpandValue> expandValueList = new ArrayList<>();
        for (ExpandField expandField : fieldList) {
            String fieldName = expandField.getName();
            String fieldValue = expandData.get(fieldName);

            if (fieldValue == null) {
                continue;
            }

            ExpandValue expandValue = new ExpandValue();
            expandValue.setValue(fieldValue);
            expandValue.setName(fieldName);
            expandValue.setRecordId(recordId);
            expandValue.setModel(model);
            expandValueList.add(expandValue);
        }
        expandValueRepository.saveBatch(expandValueList);
    }

    /**
     * 获取拓展字段
     *
     * @param recordId
     * @return
     */
    @Override
    public Map<String, String> getExpandData(Long recordId) {
        return expandValueRepository.getExpandDate(recordId);
    }
}
